package wikibooks;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 * Converts a single chapter of a wikibook.
 * To function properly, it has to receive an implementation of
 * {@link wikibooks.WikicodeConverter} through invocation of setWikicodeConverter().
 */
class ChapterConverter {

    private ConversionSettings cs;
    private BookSettings bs;
    private String chapterTitle;
    private String fullChapterTitle;
    private String shortTitle;
    private String wikicode;
    private WikicodeConverter wikicodeConverter;

    /**
     * Converts to LaTeX MediaWiki markup of book subpage from online page. If
     * BookSettings.title() is "My Book" and chapter is "Introduction", converts
     * "My Book/Introduction."
     * 
     * @param pageName
     *            name of the page to convert (ie: "Book Title/Part one/Introduction)
     */
    public ChapterConverter(BookSettings bs, ConversionSettings cs, String pageName,
            String shortTitle) {
        fullChapterTitle = pageName;
        pageName = pageName.replace(" ", "_");

        String chapterTitle = pageName;
        if (pageName.contains("/") && pageName.indexOf("/") + 1 < pageName.length()) {
            chapterTitle = pageName.substring(pageName.lastIndexOf("/") + 1);
        }
        chapterTitle = chapterTitle.replace("_", " ");

        String wikicode = Util.downloadWikicode(pageName);
        construct(bs, cs, chapterTitle, shortTitle, wikicode);
    }

    /**
     * Converts MediaWiki markup stored in File file to LaTeX.
     * 
     * @param chapterTitle
     *            page title
     * @param file
     *            text file with MediaWiki markup.
     */
    public ChapterConverter(BookSettings bs, ConversionSettings cs, String chapterTitle, String shortTitle,
            File file) {
        fullChapterTitle = chapterTitle;

        String wikicode = "";
        try {
            Scanner fileScanner = new Scanner(file);
            while (fileScanner.hasNextLine() && fileScanner.ioException() == null) {
                wikicode += fileScanner.nextLine() + "\n";
            }
            if (fileScanner.ioException() != null){
                Log.addError("Error reading chapter " + chapterTitle + ": " + fileScanner.ioException().toString() + "\n");
            }
        } catch (FileNotFoundException e) {
            Log.addError("File not found for chapter " + chapterTitle + "\n");
        }
        construct(bs, cs, chapterTitle, shortTitle, wikicode);
    }

    /**
     * Converts MediaWiki markup in String wikicode to LaTeX.
     * 
     * @param chapterTitle
     *            page title
     * @param wikicode
     *            MediaWiki markup
     */
    public ChapterConverter(BookSettings bs, ConversionSettings cs, String chapterTitle,
            String shortTitle, String wikicode) {
        fullChapterTitle = chapterTitle;
        construct(bs, cs, chapterTitle, shortTitle, wikicode);
    }

    private void construct(BookSettings bs, ConversionSettings cs, String chapterTitle,
            String shortTitle, String wikicode) {
        if (chapterTitle.contains("/")) {
            chapterTitle = chapterTitle.substring(chapterTitle.indexOf("/") + 1);
        }

        this.cs = cs;
        this.bs = bs;
        this.chapterTitle = chapterTitle;
        this.shortTitle = chapterTitle.equals(shortTitle) ? "" : shortTitle;
        this.wikicode = wikicode;

        if (fullChapterTitle.contains("/")) {
            fullChapterTitle = fullChapterTitle.substring(fullChapterTitle.indexOf("/") + 1);
        }
        fullChapterTitle = Util.removeAccents(fullChapterTitle);
    //fullChapterTitle = Util.toSafeFilename(fullChapterTitle);
    }

    public String convert() {
        // TODO test labels

        boolean isBook = bs.article == null;

        StringBuilder latex = new StringBuilder(isBook ? "\\chapter" : "\\section");
        if (shortTitle != null && !shortTitle.equals("")) {
            latex.append("[").append(shortTitle).append("]");
        }
        latex.append("{").append(chapterTitle).append("}");
        latex.append("\\label{").append(fullChapterTitle).append("}\n");
        if (bs.generateChapterLinks) {
            latex.append("\\chapterlinks{").append(chapterTitle.replace(" ", "_")).append("}\n");
        }
        latex.append("\n");

        if (wikicode != null && wikicode.length() > 0) {
            wikicodeConverter.setWikicodeName("Chapter " + chapterTitle + ":");
            latex.append(wikicodeConverter.convert(wikicode));
        }
        return latex.toString();
    }

    public void setWikicodeConverter(WikicodeConverter wc) {
        this.wikicodeConverter = wc;
    }
}
